
// cors 处理中间件
module.exports = (options,app) => {
    // const {whiteList} = options;

    
    const {
        whiteList,
        credentials,
        allowMethods
    } = options;
    
    if(!Array.isArray(whiteList)) {
        throw new Error('cors_mutiOrigin 中间件的配置 whiteList 必须传入一个数组');
    }   

    return async (ctx,next) => {
    
        const origin = ctx.request.header.origin;
        
        if(!whiteList.includes('*') && !whiteList.includes(origin)) {
            ctx.stuts = 200;
            ctx.body = '当前 origin 不能访问';
            return;
        }
        
    
        ctx.set("Access-Control-Allow-Origin",origin);
        ctx.set("Access-Control-Allow-Credentials",true);
        ctx.set("Access-Control-Request-Method","PUT,GET,POST,DELETE,OPTIONS");
        ctx.set('Access-Control-Allow-Headers',"Origin,X-Requested-With,Content-Type,Accept,cc");
        console.log('method:',ctx.method,'from host:',origin);    
        console.log(ctx.response.header);
        if (ctx.method === "OPTIONS") {
            ctx.status = 204;
            return;
          }
        await next();
    }
}